import os
from django.apps import AppConfig
from django.conf import settings
from pymongo import MongoClient
from lightgbm import LGBMRegressor
from catboost import CatBoostRegressor
from .linear_model.k8s_config_reader import parse_k8s_config


class NewModelServerConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'new_model_server'

    def ready(self):
        """
        项目初始化文件
        :return:
        """
        current_dir = os.path.dirname(os.path.abspath(__file__))
        parent_dir = os.path.dirname(current_dir)
        settings.save_model_path = os.path.join(parent_dir, "template_zip", "models")  # TODO 需要协商进行定义
        settings.model_desc = os.path.join(parent_dir, "template_zip", "model_desc.json")
        settings.save_model_path = os.path.join(parent_dir, "template_zip", "models")  # TODO 需要协商进行定义
        if not settings.save_model_path:
            os.makedirs(settings.save_model_path)

        settings.save_zip_path = os.path.join(parent_dir, "template_zip")
        settings.save_zip_file = os.path.join(parent_dir, "model.zip")
        # mongodb数据库的配置
        settings.database_name = "cement_ingredient"
        # settings.self_learning_collection_prefix = "QUALITY_INSPECTION_AVERAGE_"
        # settings.default_mongo_uri = ""
        # settings.self_DICTIONARY_1 = "DICTIONARY_1"
        # settings.self_learning_collection_name = ""
        # TODO 本地测试将下面代码打开，否则进行注释 DICTIONARY_1_anxian_勿删  QUALITY_INSPECTION_AVERAGE_1_anxian_勿删
        settings.self_learning_collection_name = "QUALITY_INSPECTION_AVERAGE_1_beichuan"
        settings.self_DICTIONARY_1 = "DICTIONARY_1_beichuan"
        settings.default_mongo_uri = "mongodb://admin:LTK58VwiytCS@10.40.0.114:27017/admin?authMechanism=SCRAM-SHA-1"

        # 非线性模型配置
        settings.nonlinear_model_name = "CatBoost"  # CatBoost 或者是 LightGBM
        settings.MODEL_DICT = {
            'CatBoost': CatBoostRegressor,
            'LightGBM': LGBMRegressor
        }
        settings.need_columns_name = []
        settings.train_optuna = {
            'loss_function': 'RMSE',
            # "loss_function": R2Loss(),
            # "eval_metric": 'R2'
        }

        # 模型名称配置
        settings.model_type_suffix = {
            "model3_1d": "model3_1d",
            "model3_n1d": "model3_n1d",
            "model28_1d": "model28_1d",  # 有一天，无3天 水泥实测值
            "model28_n1d": "model28_n1d",  # 无一天，无3天 水泥实测值
            "model28_3d": "model28_3d",  # 有一天，有3天 水泥实测值
        }
        # 线性模型配置
        settings.linear_suffix = ["linear", "linear_1d", "linear_3d"]

        # 获取大模型平台api&k8s的相关信息
        self.judge_position_get_info()

        # 请求大模型平台header中带有的参数
        settings.current_tenant_id = "1"

    def judge_position_get_info(self):
        """
        获取大模型平台api和k8s相关配置信息
        :return:
        """
        api = {
            "local": {
                "query_api": "http://product-qa.allintechinc.com/machine-learning/api/v3/model/",
                "upload_api": "http://product-qa.allintechinc.com/machine-learning/api/v2/model_import/custom/model",
                "register_api": "http://product-qa.allintechinc.com/machine-learning/api/v2/model_import/custom",
                "deploy_api": "http://product-qa.allintechinc.com/machine-learning/api/v1/model/auto/deploy",
                "monitor_api": "http://product-qa.allintechinc.com/machine-learning/api/v1/model/evaluation/upload"
            },
            "k8s": {
                "query_api": "http://machine-learning:8080/api/v3/model/",
                "upload_api": "http://machine-learning:8080/api/v2/model_import/custom/model",
                "register_api": "http://machine-learning:8080/api/v2/model_import/custom",
                "deploy_api": "http://machine-learning:8080/api/v1/model/auto/deploy",
                "monitor_api": "http://machine-learning:8080/api/v1/model/evaluation/upload"
            }
        }
        if 'KUBERNETES_SERVICE_HOST' in os.environ:
            data_dict = parse_k8s_config()
            mongo_config = data_dict["mongo"]
            settings.mongo_uri = f"mongodb://{mongo_config['user']}:{mongo_config['password']}@{mongo_config['host']}/?authSource={mongo_config['authSource']}&authMechanism={mongo_config['authMechanism']}"
            settings.periodic_interval = data_dict["train"]["periodic_interval"]
            settings.initial_interval = data_dict["train"]["initial_interval"]
            settings.query_api = api["k8s"]["query_api"]
            settings.upload_api = api["k8s"]["upload_api"]
            settings.register_api = api["k8s"]["register_api"]
            settings.deploy_api = api["k8s"]["deploy_api"]
            settings.monitor_api = api["k8s"]["monitor_api"]
            # settings.simulation_url = api["k8s"]["simulation_url"]
            settings.database_name = settings.database_name
        else:
            # 加载本地信息
            settings.mongo_uri = settings.default_mongo_uri
            settings.query_api = api["local"]["query_api"]
            settings.upload_api = api["local"]["upload_api"]
            settings.register_api = api["local"]["register_api"]
            settings.deploy_api = api["local"]["deploy_api"]
            # settings.simulation_url = api["local"]["simulation_url"]
            settings.monitor_api = api["local"]["monitor_api"]
            settings.periodic_interval = 259200  # 3天
            settings.initial_interval = 1800
            settings.database_name = "cement_ingredient"
